import { feedApi } from '/api/feed'
import { GlobalData } from '/store/state'
import { $event } from '/utils'

Page({
  data: {
    access: GlobalData.access,
    list: [] as any[],
    //瀑布流的计算
    leftHight: 0,
    rightHight: 0,
    leftList: [] as any[],
    rightList: [] as any[],
    isLastpage: false,
    liked: false,
  },
  onLoad() {
    $event.on('after:boot', this, () => {
      this.getRoot()
    })
    $event.on('after:like', this, (feed) => {
      // 更新点赞信息
      this.updateLikeStatus(feed)
    })
    this.getRoot()
    this.getList()
  },
  onShow() { },
  onPullDownRefresh() {
    this.getList()
    wx.stopPullDownRefresh()
  },
  onReachBottom() {
    this.getList(true)
  },
  getRoot() {
    wx.setNavigationBarTitle({
      title: GlobalData.access.video ? '短视频' : '推荐',
    })
    this.setData({
      access: GlobalData.access,
    })
  },
  /**
   * 更新点赞状态
   */
  updateLikeStatus(feed: any) {
    const { leftList, rightList } = this.data

    const index = leftList.findIndex((item) => item.id === feed.id)
    if (index !== -1) {
      leftList[index].has_liked = feed.has_liked
      leftList[index].like_count = feed.like_count
      this.setData({
        leftList,
      })
    }
    const index2 = rightList.findIndex((item) => item.id === feed.id)
    if (index2 !== -1) {
      rightList[index2].has_liked = feed.has_liked
      rightList[index2].like_count = feed.like_count
      this.setData({
        rightList,
      })
    }
  },
  async getList(isLoadMore = false) {
    if (isLoadMore && this.data.isLastpage) {
      wx.showToast({
        title: '没有更多了',
        icon: 'none',
        duration: 1000,
      })
      return
    }
    wx.showLoading({
      title: '加载中',
    })
    const excludes = [] as number[]
    if (isLoadMore) {
      this.data.list.forEach((item) => excludes.push(item.id))
    }
    try {
      const list = await feedApi.getRandomFeeds({
        exclude_feeds: Array.from(new Set(excludes)) as number[],
        type: 'video',
        limit: 16,
      })
      const isLastpage = list.length < 15
      let leftHight = isLoadMore ? this.data.leftHight : 0
      let rightHight = isLoadMore ? this.data.rightHight : 0
      const leftList = isLoadMore ? this.data.leftList : []
      const rightList = isLoadMore ? this.data.rightList : []
      // 末尾加10,解决高度较小的图片过多,标题占位过多导致瀑布流失效的方法
      list.forEach((item) => {
        const width =
          item.video.cover && item.video.cover.dimension ? item.video.cover.dimension.width : 320
        const height =
          item.video.cover && item.video.cover.dimension ? item.video.cover.dimension.height : 480
        if (leftHight == rightHight || leftHight < rightHight) {
          leftList.push(item)
          leftHight = leftHight + (330 / width) * height + 10
        } else {
          rightList.push(item)
          rightHight = rightHight + (330 / width) * height + 10
        }
      })
      this.setData({
        list: isLoadMore ? [...this.data.list, ...list] : list,
        leftHight,
        rightHight,
        leftList,
        rightList,
        isLastpage,
      })
    } catch (error) {
      wx.showToast({
        title: '加载失败',
        icon: 'none',
        duration: 1000,
      })
    }
    wx.hideLoading()
  },
  detail(e: WechatMiniprogram.BaseEvent) {
    if (!this.data.access.video) return
    const id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/feed/video/video?feedId=${id}`,
    })
  },
  async like(e: WechatMiniprogram.BaseEvent) {
    if (this.data.liked) return
    const index = e.currentTarget.dataset.index
    const isLeft = e.currentTarget.dataset.isleft
    const list = isLeft ? this.data.leftList : this.data.rightList
    list[index].has_liked = !list[index].has_liked
    list[index].like_count = list[index].has_liked
      ? list[index].like_count + 1
      : list[index].like_count - 1
    if (isLeft) {
      this.setData({
        leftList: list,
        liked: true,
      })
    } else {
      this.setData({
        rightList: list,
        liked: true,
      })
    }
    // list[index].has_liked?await feedApi.likeFeed(list[index].id):await feedApi.unlikeFeed(list[index].id)
    if (list[index].has_liked) {
      const res = await feedApi.likeFeed(list[index].id)
      if (res.amount) {
        $event.emit('showMessage', {
          message: '点赞成功',
          amount: res.amount,
        } as GetRewardMessageReturns)
      }
    } else {
      await feedApi.unlikeFeed(list[index].id)
    }
    this.setData({
      liked: false,
    })
  },
  toUser(e: WechatMiniprogram.BaseEvent) {
    const id = e.currentTarget.dataset.id
    return wx.navigateTo({ url: `/mine/homePage/homePage?id=${id}` })
  },
  toSource(e: WechatMiniprogram.BaseEvent) {
    const item = e.currentTarget.dataset.item
    if (item.theme) {
      wx.navigateTo({
        url: `/pages/theme/detail/detail?id=${item.theme.id}`,
      })
    } else {
      wx.navigateTo({
        url:
          item.repostable_type === 'knowledge'
            ? `/index/knowledge/detail/detail?id=${item.repostable.id}`
            : item.repostable_type === 'infos'
              ? `/index/information/detail/detail?id=${item.repostable.id}`
              : `/mall/detail/detail?commodityId=${item.repostable.id}`,
      })
    }
  },
})
